package com.example;

/**
 * @author wuyinggang
 * @Description: todo
 * @date 2021/7/2116:00
 */

import org.springframework.web.multipart.MultipartFile;

import java.util.Collection;

/**
 * 效验文件
 */
public class FileUtil {

    /**
     * 判断文件大小
     *
     * @param uploadFile 文件对象
     * @param size       大小
     * @param unit       大小单位 B，K，M ，G
     * @return
     */
    public static boolean checkFileSize(MultipartFile uploadFile, int size, String unit) {
//        long len = file.length();
        long len = uploadFile.getSize();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

    /**
     * 判断文件类型
     *
     * @param uploadFile 文件对象
     * @param suffixList 比对的后缀集合[jpg,PNg]
     * @return
     */
    public static boolean checkFileType(MultipartFile uploadFile, Collection suffixList) {
        String originalFilename = uploadFile.getOriginalFilename(); //获取原始文件名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        for (Object o : suffixList) {
            if (o.toString().equalsIgnoreCase(suffix)) {
                return true;
            }
        }
        return false;
    }
}
